var parentId = 0;
var packageId = $("#packageId").val();
var status = $("#status").val();
$(function () {
    //加载数据
    loadPackageCourseData();
   $("body").on('click','.selectCourse',function () {//选择课程
       parentId = $(this).data('select');
       selectCourse({
           selectType:"checkbox",
           type:2,
           packageId:packageId,
           callback:'selectCourseCallback'
       });
   }).on('click','#insertStage',function () {//创建阶段
       parent.layer.open({
           type: 1,
           area: ['500px'],
           btn: '确定',
           content: '<div class="m-t m-r m-l m-b"><input class="form-control" placeholder="阶段描述信息"></div>',
           skin: 'layui-layer-demo',
           title: '添加阶段',
           yes: function (index, layero) {
               var stageContext = layero.find('input:eq(0)').val();
               $.ajax({
                   url:baseloaction +'/admin/course/package/createStage',
                   type:'post',
                   dataType:'json',
                   data:{
                       'packageId':packageId,
                       'stageContext':stageContext
                   },
                   success:function (result) {
                       if(result.success==true){
                           parent.layer.close(index);
                           loadPackageCourseData();
                       }else{
                           icModale(0,result.message);
                       }
                   },
                   error:function (error) {
                       icModale(0,'系统错误，添加阶段失败');
                   }
               });
           }
       });
   }).on('click','#package-course-list-box i.fa-edit',function () {//修改价格
       var id = $(this).parent().data('id');
       parent.layer.open({
           type: 1,
           area: ['380px'],
           btn: '确定',
           content: '<div class="m-t m-r m-l m-b"><input class="form-control" placeholder="课程价格：0.0"></div>',
           skin: 'layui-layer-demo',
           title: '修改课程价格',
           yes: function (index, layero) {
               var value = layero.find('input:eq(0)').val();
                if(!/^[0-9]+(.[0-9]{1,2})?$/.test(value)){
                    icModale(0, '请输入正确的价格，如：10或10.5或10.12');
                    return;
                }
               $.ajax({
                   url: baseloaction + "/admin/course/package/updatePackagePrice",
                   data: {'id': id ,'price': value},
                   dataType: 'json',
                   success: function (response) {
                       if (response.success==true) {
                           $("#pkg-price-"+id).text(value);
                           parent.layer.close(index);
                       } else {
                           icModale(0, response.message);
                       }
                   },
                   error: function () {
                       icModale(0, '系统繁忙，更新价格失败');
                   }
               });
           }
       });
   }).on('click','#package-course-list-box i.fa-crosshairs',function () {//修改排序
       var id = $(this).parent().data('id');
       parent.layer.open({
           type: 1,
           area: ['380px'],
           btn: '确定',
           content: '<div class="m-t m-r m-l m-b"><input class="form-control" placeholder="排序值" value="0"></div>',
           skin: 'layui-layer-demo',
           title: '修改排序值',
           yes: function (index, layero) {
               var value = layero.find('input:eq(0)').val();
               if(!/^[0-9]\d*$/.test(value)){
                   icModale(0, '请输入整数');
                   return;
               }
               $.ajax({
                   url: baseloaction + "/admin/course/package/updatePackageCourseSort",
                   data: {'id': id ,'sort': value},
                   dataType: 'json',
                   success: function (response) {
                       if (response.success==true) {
                           $("#pkg-sort-"+id).text(value);
                           parent.layer.close(index);
                       } else {
                           icModale(0, response.message);
                       }
                   },
                   error: function () {
                       icModale(0, '系统繁忙，更新排序失败');
                   }
               });
           }
       });
   }).on('click','#package-course-list-box i.fa-toggle-off',function () {//设置为必选
        var id = $(this).parent().data('id');
       updateStatus(id,1);
   }).on('click','#package-course-list-box i.fa-toggle-on',function () {//设置为可选
       var id = $(this).parent().data('id');
       updateStatus(id,2);
   }).on('click','#package-course-list-box i.fa-trash',function () {//删除
       var id = $(this).parent().data('id');
       var em = $(this);
       icModale(2, "确认要删除该课程的关联？", 3, function () {
           deleteDate(em,id,1);
       });
   }).on('click','#package-course-list-box i.fa-close',function () {//删除阶段
       var em = $(this);
       var id = em.parent().data('id');
       icModale(2, "确认要删除该阶段？", 3, function () {
           deleteDate(em,id,2);
       });
   }).on('click','#cancelLast',function () {//取消上一步
       window.history.go(-1);
   }).on('click','#saveReturn,#saveCancel',function () {//返回
       window.location.href = baseloaction +'/admin/course/package/toPackageCourseList';
   });

    /**
     * 删除数据
     * @param em 操作的元素
     * @param id 记录ID
     * @param type 类型，1删除课程，2删除阶段
     */
   function deleteDate(em,id,type) {
       $.ajax({
           url:baseloaction +'/admin/course/package/deletePackageCourse',
           type:'post',
           dataType:'json',
           data:{
               'packageId':packageId,
               'ids':id
           },
           success:function (result) {
               if(result.success==true){
                   if(type==1){//删除课程
                       var tables = em.parents('table');
                       var list = $(tables).find('tr:not(.jqgfirstrow)');
                       if(list!=null && list.length>1){
                           em.parents('tr').remove();
                       }else{
                           loadPackageCourseData();
                       }
                   }else if(type==2){//删除阶段
                       var list = $("#package-course-list-box .oc-ibox-content");
                       if(list!=null && list.length>1){
                           em.parents('.oc-ibox-content').remove();
                       }else{
                           loadPackageCourseData();
                       }
                   }
               }else{
                   icModale(0, result.message);
               }
           },
           error:function (error) {
               icModale(0, '系统繁忙，删除课程失败');
           }

       });
   }
    /**
     * 修改状态
     * @param id 记录ID
     * @param status 状态，1必选，2可选
     */
   function updateStatus(id,status) {
        $.ajax({
            url: baseloaction + "/admin/course/package/updatePackageCourseRequired",
            type:'post',
            data: {'id': id ,'required': status},
            dataType: 'json',
            success: function (response) {
                if (response.success==true) {
                    var statusEm = $("#pkg-status-action-"+id);
                    if(status==1){
                        $("#pkg-required-"+id).text('是');
                        statusEm.attr("data-original-title",'取消必选');
                        statusEm.html('<i class="fa fa-toggle-on"></i>');
                    }
                    if(status==2){
                        $("#pkg-required-"+id).text('否');
                        statusEm.attr("data-original-title",'设为必选');
                        statusEm.html('<i class="fa fa-toggle-off"></i>');
                    }
                } else {
                    icModale(0, response.message);
                }
            },
            error: function () {
                icModale(0, '系统繁忙，状态修改失败');
            }
        });
   }
});

/**
 * 加载套餐课程数据
 */
function loadPackageCourseData() {
    $.ajax({
        url:baseloaction +'/admin/course/package/ajaxPackageCourse',
        type:'post',
        dataType:'text',
        data:{
            'packageId':packageId,
            'status':status
        },
        success:function (result) {
            $("#package-course-list-box").html(result);
            setEndTr();
            $('[data-toggle=tooltip]').tooltip();
        }
    });
}

/**
 * 选择课程回调
 * @param result 回调数据
 */
function selectCourseCallback(result) {
    if(result!=null && result.length>0){
        var courseIds = '';
        $.each(result,function (index,course) {
            if(index<result.length-1){
                courseIds +=course.id+',';
            }else{
                courseIds +=course.id;
            }
        });
        $.ajax({
            url:baseloaction +'/admin/course/package/savePackageCourse',
            type:'post',
            dataType:'json',
            data:{
                'parentId':parentId,
                'packageId':packageId,
                'courseIds':courseIds
            },
            success:function (result) {
                if(result.success==true){
                    loadPackageCourseData();
                }else{
                    icModale(0,result.message);
                }
            },
            error:function (error) {
                icModale(0,'系统错误，添加课程失败');
            }
        });
    }
    parentId = 0;
}

function setEndTr(){
 var tables =  $("#package-course-list-box .table-xs-content");
    $.each(tables, function (index, em) {
        //设置最后一行的显示标签
        if (tables != null && tables.length > 0) {
                var trList = $(em).find("tr");
                if (trList.length > 2) {
                    //获取最后一行显示标签
                    var as = $(trList[trList.length - 1]).find('td').find("a");
                    $.each(as, function (index, em) {
                        em.setAttribute('data-placement',"top");
                    });
                }else{
                    var as = $(trList[trList.length - 1]).find('td').find("a");
                    $.each(as, function (index, em) {
                        em.setAttribute('data-placement',"left");
                    });
                }
        }

    });
}